<?php
// +----------------------------------------------------------------------
// | 文件: index.php
// +----------------------------------------------------------------------
// | 功能: 提供todo api接口
// +----------------------------------------------------------------------
// | 时间: 2021-11-15 16:20
// +----------------------------------------------------------------------
// | 作者: rangangwei<gangweiran@tencent.com>
// +----------------------------------------------------------------------

namespace app\controller;

use Error;
use Exception;
use app\model\Counters;
use think\Model;
use think\response\Html;
use think\response\Json;
use think\facade\Log;

class Index
{

    /**
     * @return Json
     */
    public function index(): Json
    {
        $dataRow = [];
        if($_SERVER['REQUEST_METHOD'] == 'POST') {

            $headers = array();
            foreach ($_SERVER as $key => $value) {
                if ('HTTP_' == substr($key, 0, 5)) {
                    $headers[$key] = $value;
                }
            }
//            $unionId = $_SERVER['HTTP_X_WX_UNIONID'];
            $unionId = 'oOcKY6ODFmWmPDr9Irs8ezPbE12w';

            $openId = 'omnJQwph51NkUJNoFHq08zUzP5Dk';
//            $openId = $_SERVER['HTTP_X_WX_OPENID'];
//            $access_token = $_SERVER['HTTP_X_WX_CLOUDBASE_ACCESS_TOKEN'];
            $access_token = 'CLIBEoACiJrjSZ_xwCsYy9EHn-8Z0cTyqSus1JQvWapPwd2uyOoo-vAkd2EcbUSYwTKG-y8rrbxGwQnucXFaj1DSioWHMob4WBvFGjRvINznrTwPShbiX3KVQJfHUFS1V7C9sjOyXVW_e6CnyhoemfALpcrIUDYPmZ0tKRC_OkgreDChek6QM_k_R1i_JxV9BvnmEH9tLyO0qi4Grh9sjhTnN3097qRndUDjtIrLQ5HS2sNUkb9UQtbAqkVxr7yqEyU0ifVLoP1J3UC8a8R0QsFRXHwCDOk-d6fqECr9Mm4InSmYoHThZL78bISFhfjfzazCvmPU8c1YypUfcL6qr23CmbfMkhgFIAA';

            $input = file_get_contents("php://input");
            if ($temp_input = json_decode($input, true)) {
//                $openid = $temp_input['FromUserName'];
//                $content = $temp_input['Content'];
                $type = $temp_input['MsgType'];
                if ($type == 'text') {

                    $dataRow = [
                        'openId' => $openId,
                        'unionId' => $unionId,
                        'tongbuID' => 'mosaic123456',
                    ];

                    $env = 'cloud1-5ggm8rve2b055e97';
//                    $fun_name = 'tongbuUser';
                    $fun_name = 'tongbuUid';
//                    $url = "https://api.weixin.qq.com/tcb/invokecloudfunction?env={$env}&name={$fun_name}";
                    $url = "https://api.weixin.qq.com/tcb/invokecloudfunction?access_token={$access_token}&env={$env}&name={$fun_name}";
                    try {

                        $res = $this->updateUser($dataRow,$url);
//                        var_dump(json_encode($res));
//                    $res2 = $this->updateUser($dataRow,$url);
//                    $res = '11';

                        $dataRow = [
                            'openId' => $openId,
                            'unionId' => $unionId,
                            'content' => json_encode($headers),
                            'res' => json_encode($res),
                        ];

                        file_put_contents('mosaic.txt',json_encode($res));

                        $counters = new Counters;

                        $counters->create(
                            $dataRow,
                            [
                                'openId',
                                'unionId',
                                'content',
                                'res'
                            ],
                            true
                        );

                    }catch (Exception $e){
                        file_put_contents('mosaic.txt',$e->getMessage());
                    }




                }
            }
        }
        $res = [
            "code" => 0,
            "data" =>  $dataRow
        ];
        Log::write('getCount rsp: '.json_encode($res));
        return json($res);
    }

    public function updateUser($data,$url){
        $data  = json_encode($data);
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        //        {"HTTP_CONNECTION":"keep-alive","HTTP_CONTENT_LENGTH":"175","HTTP_CONTENT_TYPE":"application\/json",
//            "HTTP_X_WX_UNIONID":"oOcKY6ODFmWmPDr9Irs8ezPbE12w",
//            "HTTP_X_WX_CLOUDBASE_ACCESS_TOKEN":"CLIBEoACiJrjSZ_xwCsYy9EHn-8Z0cTyqSus1JQvWapPwd2uyOoo-vAkd2EcbUSYwTKG-y8rrbxGwQnucXFaj1DSioWHMob4WBvFGjRvINznrTwPShbiX3KVQJfHUFS1V7C9sjOyXVW_e6CnyhoemfALpcrIUDYPmZ0tKRC_OkgreDChek6QM_k_R1i_JxV9BvnmEH9tLyO0qi4Grh9sjhTnN3097qRndUDjtIrLQ5HS2sNUkb9UQtbAqkVxr7yqEyU0ifVLoP1J3UC8a8R0QsFRXHwCDOk-d6fqECr9Mm4InSmYoHThZL78bISFhfjfzazCvmPU8c1YypUfcL6qr23CmbfMkhgFIAA",
//            "HTTP_X_WX_OPENID":"omnJQwph51NkUJNoFHq08zUzP5Dk",
//            "HTTP_X_WX_APPID":"wxcc7d452635a77e1d",
//            "HTTP_X_WX_REGION":"ap-shanghai",
//            "HTTP_X_WX_ENV":"prod-7gk427ez82db24c3",
//            "HTTP_HOST":"thinkphp-nginx-25l3-prod-7gk427ez82db24c3-1309418688.ap-shanghai.internal-run.tcloudbase.com",
//            "HTTP_X_WX_SERVICE":"thinkphp-nginx-25l3",
//            "HTTP_X_WX_SOURCE":"other",
//            "HTTP_ACCEPT":"*\/*",
//            "HTTP_X_CLOUDBASE_SESSIONTOKEN":"rjaj1o24NpbIcsRcZT19CdDIJgEiywda54f639cf6da815a89b58d2299b2ccd1cuductnsB4mDzC-DncliB_Md-utoiOFj5ZPQrpMX8GIDWAIDPHTthw2aT4-NfJwfPO65OyQnmrqfG_f0dy7_re5ZnqJXR2bEIZ6SA_D_DWn-pjv2hCnBY9u-xbaTh6WxXPwpUHch_MKklF_kiPvVaC3Lcng4XOpxe1ASBarvhhZn4hE1JTZx7JN0Ys7KdERoI3fOW-Bz7XWcoQCGLO4oW0BY0tHi-rpejhsBvstpmb-8SYuFWKB9EbbiC4DhSzeL7Cn8HZwclUy9tw4LoTeP4m7N1jt28bUb49md90pKhpW-8sQ4ILiPmEONFlm-zHUsm4uHqJgEqKi0LOzk77SmEeO5syRVe1OBVr7d78pMlupE",
//            "HTTP_X_CLOUDBASE_AUTHORIZATION":"1.0 TC3-HMAC-SHA256 Credential=AKIDOLvy-tuVE0jN3zhztLUng_tClznC9hXx-kXAs9ZH3Er-f684i21g7sIoppWrkuWV\/2022-01-25\/tcb\/tc3_request, SignedHeaders=content-type;host, Signature=903451c0bd8e4e4ae7f48ecc195a7102ebee52ca635d47e719a1af4e572aa4a1",
//            "HTTP_X_CLOUDBASE_TIMESTAMP":"1643102972",
//            "HTTP_X_CLOUDBASE_TRACE":"ZGEyZDFlNDU4NzQzNDljMWJmMmNlZWI0OGU1ZTcwOTgsODZhMTgwODZhYzM4N2VmOSxvbg==","HTTP_X_FORWARDED_PROTO":"http",
//            "HTTP_X_FORWARDED_HOST":"thinkphp-nginx-25l3-prod-7gk427ez82db24c3-1309418688.ap-shanghai.internal-run.tcloudbase.com",
//            "HTTP_USER_AGENT":"got (https:\/\/github.com\/sindresorhus\/got)"}
        return json_decode($output,true);
    }

    /**
     * 获取todo list
     * @return Json
     */
    public function getCount(): Json
    {
//        file_put_contents('/app/mosaic.txt','1111');
//        return json(['success']);
        $counters = new Counters;
        $counters->create(
            [
                'openId' => 'mosaic123456',
                'unionId' => 'mosaic123456',
                'content' => 'mosaic123456',
            ],
            [
                'openId',
                'unionId',
                'content',
            ],
            true
        );
        return json(['success']);
        $dataRow = [];
        $res = [];
        $access_token = '';
        $headers = [];
        if($_SERVER['REQUEST_METHOD'] == 'POST') {

            foreach ($_SERVER as $key => $value) {
//                if ('HTTP_' == substr($key, 0, 5)) {
                    $headers[$key] = $value;
//                }
            }
            try {


            $unionId = $_SERVER['HTTP_X_WX_UNIONID'];
//            $unionId = 'oOcKY6ODFmWmPDr9Irs8ezPbE12w';
            $openId = $_SERVER['HTTP_X_WX_OPENID'];
//            $openId = 'omnJQwph51NkUJNoFHq08zUzP5Dk';
//            $access_token = $_SERVER['HTTP_X_WX_CLOUDBASE_ACCESS_TOKEN'];
//            $access_token = 'wx26c616931645f498@'.file_get_contents('/.tencentcloudbase/wx/cloudbase_access_token');
//            $access_token = file_get_contents('/.tencentcloudbase/wx/cloudbase_access_token');
            $access_token = 'CLIBEoACiJrjSZ_xwCsYy9EHn-8Z0cTyqSus1JQvWapPwd2uyOoo-vAkd2EcbUSYwTKG-y8rrbxGwQnucXFaj1DSioWHMob4WBvFGjRvINznrTwPShbiX3KVQJfHUFS1V7C9sjOyXVW_e6CnyhoemfALpcrIUDYPmZ0tKRC_OkgreDChek6QM_k_R1i_JxV9BvnmEH9tLyO0qi4Grh9sjhTnN3097qRndUDjtIrLQ5HS2sNUkb9UQtbAqkVxr7yqEyU0ifVLoP1J3UC8a8R0QsFRXHwCDOk-d6fqECr9Mm4InSmYoHThZL78bISFhfjfzazCvmPU8c1YypUfcL6qr23CmbfMkhgFIAA';

            $counters = new Counters;
            $counters->create(
                [
                    'openId' => $openId,
                    'unionId' => $unionId,
                    'content' => 'mosaic123456',
                ],
                [
                    'openId',
                    'unionId',
                    'content',
                ],
                true
            );
            }catch(Exception $e){
                file_put_contents('/app/mosaic.txt',$e->getMessage());
            }
            $input = file_get_contents("php://input");
            if ($temp_input = json_decode($input, true)) {
//                $openid = $temp_input['FromUserName'];
//                $content = $temp_input['Content'];
                $type = $temp_input['MsgType'];
                if ($type == 'text') {

                    $dataRow = [
                        'openId' => $openId,
                        'unionId' => $unionId,
                        'content' => 'mosaic123456',
                    ];

                    $env = 'cloud1-5ggm8rve2b055e97';
//                    $fun_name = 'tongbuUser';
                    $fun_name = 'tongbuByUid';

                    try {
                        $counters = new Counters;
                        $counters->create(
                            $dataRow,
                            [
                                'openId',
                                'unionId',
                                'content',
                            ],
                            true
                        );

                        $url = "https://api.weixin.qq.com/tcb/invokecloudfunction?env={$env}&name={$fun_name}";
//                    $url = "https://api.weixin.qq.com/tcb/invokecloudfunction?access_token={$access_token}&env={$env}&name={$fun_name}";
//                    $url = "https://api.weixin.qq.com/tcb/invokecloudfunction?cloudbase_access_token={$access_token}&env={$env}&name={$fun_name}";

                        $res = $this->updateUser($dataRow,$url);

                        $dataRow = [
                            'openId' => $openId,
                            'unionId' => $unionId,
                            'content' => $access_token,
                            'res' => json_encode($res),
                        ];
                        $counters = new Counters;
                        $counters->create(
                            $dataRow,
                            [
                                'openId',
                                'unionId',
                                'content',
                                'res'
                            ],
                            true
                        );
                    }catch (Exception $e){
                        file_put_contents('/app/mosaic.txt',$e->getMessage());
                    }
                }
            }
        }
        $res = [
            "code" => 0,
            "data" =>  json_encode($dataRow),
            "res" =>  json_encode($res),
            "token" =>  $access_token,
        ];
        Log::write('getCount rsp: '.json_encode($res));
        return json($res);
    }


    /**
     * 根据id查询todo数据
     * @param $action `string` 类型，枚举值，等于 `"inc"` 时，表示计数加一；等于 `"reset"` 时，表示计数重置（清零）
     * @return Json
     */
    public function updateCount($action): Json
    {
        try {
            if ($action == "inc") {
                $data = (new Counters)->find(1);
                if ($data == null) {
                    $count = 1;
                }else {
                    $count = $data["count"] + 1;
                }
    
                $counters = new Counters;
                $counters->create(
                    ["count" => $count, 'id' => 1],
                    ["count", 'id'],
                    true
                );
            }else if ($action == "clear") {
                Counters::destroy(1);
                $count = 0;
            }

            $res = [
                "code" => 0,
                "data" =>  $count
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        } catch (Exception $e) {
            $res = [
                "code" => -1,
                "data" => [],
                "errorMsg" => ("更新计数异常" . $e->getMessage())
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        }
    }
}
